// order//order/cart/index.js
var wxpay = require('../../../utils/pay.js');
const utils = require('../../../utils/util.js');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    cartResult: [],
    sumPrice: 0,
    createUid: 0,
    isEditor: false,
    isCoupon: 0,
    stockNumber: 0,
    mobile: '',
    expireTime: '',
    saleUid: 0,
    remark: '',
    jump: 0,

    selProvince: '选择省',
    provinces: [],
    citys: [],
    districts: [],
    regions:[],    //选中的区域
  },
  editor: function () {
    this.setData({
      isEditor: !this.data.isEditor
    })
  },
  toClass: function () {
    wx.reLaunch({
      url: '/pages/classes-new/index',
    })
  },
  delProducts: function () {
    let that = this;
    let pids = '';
    let selList = "_";
    let cartResult = that.data.cartResult;
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].IsSelected == 1) {
        pids += cartResult[i].OrderProductInfo.Pid + ',';
      }
    }
    pids = pids.substr(0, pids.length - 1);
    if (pids == '') {
      wx.showToast({
        title: '请选择商品',
        mask: true
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否删除?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Cart/DelProducts?pids=' + pids + '&uid=' + app.globalData.userInfo.Uid + '&selList=' + selList,
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  title: '删除成功'
                })
                that.getCart(that.data.createUid);
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.seltoid) {
      this.getCart(options.seltoid);
      this.data.createUid = options.seltoid;
    } else {
      this.getInfo();
    }
    if (options.isCoupon) {
      this.setData({
        isCoupon: options.isCoupon
      })
      if(options.isCoupon==2 || options.isCoupon==3){
        this.getRegion(0,0,'');        
      }      
      if(options.isCoupon==2){
        wx.setNavigationBarTitle({title: '索取资料'})
      }
    }
    if (options.stockNumber) {
      this.setData({
        stockNumber: options.stockNumber
      })
    }
    if (options.bossname) {
      this.setData({
        name: options.bossname
      })
    }    
    if (options.saleUid) {
      this.setData({
        saleUid: options.saleUid
      })
    }
    if (options.jump) {
      this.data.jump = options.jump;
    }    
    
    let mobile = '';
    if (app.globalData.userInfo) {
      mobile = app.globalData.userInfo.Mobile;
    }
    this.setData({
      mobile: mobile
    })
  },
  // 获取购物车数据
  getCart: function (createUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Cart/Index?uid=' + app.globalData.userInfo.Uid + '&createUid=' + createUid + '&isExtend=1',
      success: function (res) {
        if (res.data.Code == 0) {
          let extendList = res.data.Data.ExtendList;
          let cartResult = [];
          let expireTime = '';
          if (res.data.Data.StoreCartList.length > 0) {
            cartResult = res.data.Data.StoreCartList[0].CartProductList;
            if (that.data.isCoupon == 1) {
              that.getStock(cartResult[0].OrderProductInfo.Pid);
            }
            for (let i = 0; i < cartResult.length; i++) {
              if (cartResult[i].OrderProductInfo.ShowImg.indexOf('ps') != -1) {
                cartResult[i].OrderProductInfo.ShowImg = utils.formatAvaterByProHead(cartResult[i].OrderProductInfo.ShowImg);
              } else {
                cartResult[i].OrderProductInfo.ShowImg = utils.formatAvater(cartResult[i].OrderProductInfo.ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
              }
              cartResult[i].OrderProductInfo.OptionName = '';
              if (cartResult[i].OrderProductInfo.OptionIds) {
                that.getProductOptionList(cartResult[i].OrderProductInfo.OptionIds, function (name) {
                  cartResult[i].OrderProductInfo.OptionName = name;
                });
              }
            }
          }
          if (extendList && extendList.length > 0) {
            expireTime = extendList[0].SendEndTime.substr(0, 10);
          } else {
            expireTime = '';
          }
          setTimeout(function () {
            that.setData({
              cartResult: cartResult,
              expireTime: expireTime,
              sumPrice: res.data.Data.OrderAmount
            })
          }, 500);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  // 产品规格
  getProductOptionList: function (optionids, callback) {
    wx.request({
      url: app.globalData.host + '/api/product/GetProductOptionList?optionIds=' + optionids,
      success: function (res) {
        if (res.data.Code == 0) {
          let name = '';
          let list = res.data.Data;
          for (let i = 0; i < list.length; i++) {
            if (list[i].OptionList.length > 1) {
              let potionlist = list[i].OptionList;
              for (let j = 0; j < potionlist.length; j++) {
                name += potionlist[j].Name + '/';
              }
            } else {
              name += list[i].OptionList[0].Name + '/';
            }

          }
          callback(name.substr(0, name.length - 1));
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  getInfo: function () {
    let that = this;
    let cardid = wx.getStorageSync("cardId");
    if (cardid) {
      wx.request({
        url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardid,
        success: function (res) {
          if (res.data.Code == 0) {
            that.getCart(res.data.Data.Uid);
            that.data.createUid = res.data.Data.Uid;
            that.setData({
              name: res.data.Data.Company
            })
          }
        }
      })
    }
  },
  isSelect: function(){
    let cartResult = this.data.cartResult;
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].IsSelected) {
        return true;
      }
    }
    return false;
  },
  toPayOrder: function () {
    let that = this;
    if(!this.isSelect()){
      utils.showToast('请选择商品');
      return;
    } 
    wx.navigateTo({
      url: '../orderPay/index?sel=&sumprice=' + this.data.sumPrice +'&createUid=' + that.data.createUid + '&saleUid=' + that.data.saleUid,
    })
  },
  toPayOrder2: function () {
    let cartResult = this.data.cartResult;
    let sel = '';
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].IsSelected) {
        sel += '0_' + cartResult[i].OrderProductInfo.Pid + ',';
      }
    }
    sel = sel.substr(0, sel.length - 1);
    if (sel == '') {
      utils.showToast('请选择商品');
      return;
    } 
    wx.navigateTo({
      url: '../orderPay/index?sel=' + sel +'&createUid=' + that.data.createUid + '&saleUid=' + that.data.saleUid,
    })
  },
  getStock: function (pid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/Product?pid=' + pid + '&isExtend=1',
      success: function (res) {
        if (res.data.Code == 0) {
          var p = res.data.Data;
          that.setData({
            stockNumber: p.StockNumber
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      },
    })
  },

  // 转为unicode 编码
  encodeUnicode: function (str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
      res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
  },

  addShopCar: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.pid;
    let optionIds = e.currentTarget.dataset.optionids;
    let buynum = e.currentTarget.dataset.buynum;
    wx.request({
      url: app.globalData.host + '/api/Store/Product?pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {
          var p = res.data.Data;
          if (p.ProductInfo.State == 1) {
            that.showToast('商品已下架'); return;
          }
          if (p.StockNumber <= buynum) {
            that.showToast('商品库存不足'); return;
          }
          if (p.SinglePromotionInfo) {
            if (p.SinglePromotionInfo.DayBuyCount > 0) {//每天限购一份
              that.showToast('每天限购一份'); return;
            } else {
              that.showToast('限购一份'); return;
            }
          }
          that.addCart(pid, optionIds);          
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      },
    })
  },

  addShopCarCoupon: function (e) {
    var that = this;
    let stock = that.data.stockNumber;
    var pid = e.currentTarget.dataset.pid;
    let buynum = e.currentTarget.dataset.buynum;
    if (stock <= buynum) {
      wx.showModal({
        title: '提示',
        content: '商品库存不足',
        showCancel: false
      })
      return;
    }
    that.addCart(pid, '');
  },

  //加购物车
  addCart: function(pid,optionIds){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: pid,
        buyCount: 1,
        optionIds: optionIds,
        createUid: that.data.createUid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.getCart(that.data.createUid);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  sumOrder: function (e) {
    let that = this;
    var uid = app.globalData.userInfo.Uid // 用户登录 uid
    let cartResult = that.data.cartResult;
    let mobile = that.data.mobile;
    let jump = that.data.jump;  // 1 共享卖券, 11 云加盟
    let packJJKPid = 0;//玖玖卡套餐pid
    let selProvince = that.data.selProvince.replace('选择省','');
    if (!uid) {
      that.showToast('获取用户信息失败'); return;
    }
    if (!mobile) {
      that.showToast('请填写手机号'); return;
    }
    if(that.data.isCoupon==3 && selProvince==''){
      that.showToast('请选择区域'); return;
    }
    
    wx.request({
      url: app.globalData.host + '/api/product/GetCardProduct',
      success: function (res) {
        if (res.data.Code == 0) {
          let list = res.data.Data;
          if (list.length > 0) {
            packJJKPid = list[1].Pid;
            for (let i = 0; i < list.length; i++) {
              if (list[i].Pid == cartResult[0].OrderProductInfo.Pid) {//购买玖玖卡、玖玖卡套餐
                jump = 4;
              }
            }
          }
          that.submitOrderV2(jump,packJJKPid);
        } else {
          that.submitOrderV2(jump,packJJKPid);
        }
      }
    })
  },

  submitOrderV2: function (jump,packJJKPid) {
    let that = this;
    let cartResult = that.data.cartResult;
    let sellist = '0_' + cartResult[0].OrderProductInfo.Pid;
    let mobile = that.data.mobile;
    let tagindex = 4;
    var regions = that.data.selProvince ?  that.data.selProvince + that.data.selCity + that.data.selDistrict : '';
    regions = regions.replace('选择省','').replace('选择市','').replace('选择区','');
    if (jump == 4) {
      tagindex = 5;
    }    
    if(regions){
      that.data.remark +=' 加盟区域： ' + regions ;
    }    
    
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: 0,//配送地址id
      SelList: sellist,//'0_583674',//选中的购物车项键列表
      BuyerRemark: that.data.remark,//备注
      CreateUid: that.data.createUid,
      CardDiscountMoney: 0,
      CardItemId: 0,
      PackMoney: 0,
      Mobile: mobile,
      Consignee: '',
      SaleUid: that.data.saleUid,
      Jump: jump,
      Regions: regions
    }

    wx.showLoading({title: '提交中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/order/SubmitOrderV2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        } else {
          var oid = res.data.Data;
          let url = '/merchant/merchants/myCardCoupon/index?tagindex=' + tagindex;
          //判断是否买过玖玖卡
          wx.request({
            url: app.globalData.host + '/api/Coupon/GetDirectPromotion?uid=' + app.globalData.userInfo.Uid + '&createUid=' + that.data.createUid + '&payType=wechat',
            success: function (ress) {
              if (ress.data.Code == 0) {
                if (ress.data.Data.isBuy || jump != 4 || cartResult[0].OrderProductInfo.Pid == packJJKPid) {//已有玖玖卡、不是购买玖玖卡、玖玖卡套餐
                  that.toredirect(oid, url, jump);
                } else {//购买玖玖卡
                  url = '/merchant/merchants/myCardCoupon/index?tagindex=' + tagindex + '&showWxcard=1';
                  that.toredirect(oid, url, jump);
                }
              } else {
                that.toredirect(oid, url, jump);
              }
            }
          })
        }
      }
    })
  },

  toredirect: function (oid, url, jump) {
    let that = this;
    if (oid == 0) {
      wx.showToast({title: '支付成功', duration: 1000})
      wx.reLaunch({url: url})
    } else {
      if (that.data.saleUid > 0 || jump == 4 || jump == 11) {
        wxpay.wxpay(app, oid, 2, url);  //卖券、云加盟
      } else {
        wxpay.wxpayWm(app, oid, url);   //外卖支付接口
      }
    }
  },

  //获取手机号
  getPhoneNumber: function (e) {
    var that = this;
    utils.getMobile(e,function(mobile){
      if(mobile){
        that.setData({
          mobile: mobile
        });
      }      
    });   
  },

  jianShopCar: function (e) {
    let that = this;
    var pid = e.currentTarget.dataset.pid;
    let price = e.currentTarget.dataset.shopprice;
    let count = e.currentTarget.dataset.count;
    let optiondIds = e.currentTarget.dataset.optionids;
    if (count < 2) {
      wx.showModal({
        title: '提示',
        content: '是否删除?',
        success: function (res) {
          if (res.confirm) {
            that.jianShopCarConfirm(pid, price, count, optiondIds);
          }
        }
      })
    } else {
      that.jianShopCarConfirm(pid, price, count, optiondIds);
    }
  },
  jianShopCarConfirm: function (pid, price, count, optionids) {
    var that = this;
    let sumPrice = that.data.sumPrice;
    let cartResult = that.data.cartResult;
    let sellist = '';
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].OrderProductInfo.Pid == pid) {
        sellist = '0_' + pid;
        sumPrice -= price;
        break;
      }
    }
    wx.request({
      url: app.globalData.host + '/api/cart/ChangeProductCount',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: pid,
        buyCount: count - 1,
        selList: sellist,
        createUid: that.data.createUid,
        optionIds: optionids
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.getCart(that.data.createUid);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //输入框
  blurNumber: function (e) {
    if (e.detail.value < 0) {
      return
    } else {
      var that = this;
      let cartResult = that.data.cartResult;
      var pid = e.currentTarget.dataset.pid;
      let price = e.currentTarget.dataset.shopprice;
      let optionids = e.currentTarget.dataset.optionids;
      let sumPrice = that.data.sumPrice;
      let sellist = '';
      for (let i = 0; i < cartResult.length; i++) {
        if (cartResult[i].OrderProductInfo.Pid == pid) {
          sellist = '0_' + pid;
          sumPrice -= price;
          break;
        }
      }
      wx.request({
        url: app.globalData.host + '/api/cart/ChangeProductCount',
        data: {
          pid: pid,
          buyCount: e.detail.value,
          uid: app.globalData.userInfo.Uid,
          selList: sellist,
          createUid: that.data.createUid,
          optionIds: optionids
        },
        success: function (res) {
          if (res.data.Code == 0) {
            that.getCart(that.data.createUid);
          } else {
            wx.showToast({
              title: '系统错误',
              content: res.data.Message
            })
          }
        }
      })
    }
  },
  jianShopCarCoupon: function (e) {
    let that = this;
    var pid = e.currentTarget.dataset.pid;
    let price = e.currentTarget.dataset.shopprice;
    let count = e.currentTarget.dataset.count;
    if (count < 2) {
      wx.showModal({
        title: '提示',
        content: '是否删除?',
        success: function (res) {
          if (res.confirm) {
            that.jianShopCarCouponConfirm(pid, price, count);
          }
        }
      })
    } else {
      that.jianShopCarCouponConfirm(pid, price, count);
    }
  },
  jianShopCarCouponConfirm: function (pid, price, count) {
    var that = this;
    let sumPrice = that.data.sumPrice;
    let cartResult = that.data.cartResult;
    let sellist = '';
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[0].OrderProductInfo.Pid == pid) {
        sellist = '0_' + pid;
        sumPrice -= price;
        break;
      }
    }
    wx.request({
      url: app.globalData.host + '/api/cart/ChangeProductCount',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: pid,
        buyCount: count - 1,
        selList: sellist,
        createUid: that.data.createUid,
        optionIds: ''
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.getCart(that.data.createUid);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  selectGoods: function (e) {
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    let price = parseFloat(e.currentTarget.dataset.shopprice);
    let count = parseInt(e.currentTarget.dataset.count);
    let sumPrice = that.data.sumPrice;
    let cartResult = that.data.cartResult;
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].OrderProductInfo.Pid == pid) {
        cartResult[i].IsSelected = !cartResult[i].IsSelected;
        if (cartResult[i].IsSelected) {
          sumPrice = parseFloat(sumPrice) + parseFloat(count * price);
        } else {
          sumPrice = parseFloat(sumPrice) - parseFloat(count * price);
        }
        that.setData({
          cartResult: cartResult,
          sumPrice: parseFloat(sumPrice).toFixed(2)
        })
      }
    }
  },
  bindRemark: function (e) {
    let remark = e.detail.value;
    this.setData({
      remark: remark
    })
  },
  bindLinkman: function(e){
    this.setData({
      linkman: e.detail.value
    })
  },
  toEmail: function(e){
    let that = this;
    var uid = app.globalData.userInfo.Uid // 用户登录 uid
    let pid = e.currentTarget.dataset.pid;
    var regions = that.data.selProvince ?  that.data.selProvince + that.data.selCity + that.data.selDistrict : '';
    regions = regions.replace('选择省','').replace('选择市','').replace('选择区','');
    if (!uid) {
      that.showToast('获取用户信息失败'); return;
    }
    if (!that.data.linkman) {
      that.showToast('请填写联系人'); return;
    }
    if (that.data.mobile=='') {
      that.showToast('请填写手机号'); return;
    }
    if (regions=='') {
      that.showToast('请选择区域'); return;
    }

    wx.showLoading({title: '提交中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/product/SendJoinEmail?uid='+ uid+ '&pid='+ pid,
      data:{
        pid: pid,
        mobile: that.data.mobile,
        linkman: that.data.linkman,
        remark: that.data.remark,
        regions: regions
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          that.showToast('提交成功，专员会尽快联系你');
        } 
      }
    })
  },
 
 //获取省、市、区
 getRegion: function (index,id,name) {
  var that = this;
  var paths=[
    '/api/Tool/ProvinceList',
    '/api/Tool/CityList?provinceId=' + id,
    '/api/Tool/CountyList?cityId=' + id
  ]
  wx.request({
    url: app.globalData.host + paths[index],
    success: function (res) {
      var data = JSON.parse(res.data.Data);          
      if(index == 0){
        that.setData({
          provinces: data,
          selProvince: '选择省',
          selCity: '',
          selDistrict: ''
        })
      }
      if(index == 1){
        that.setData({
          citys: data,
          selProvince: name,
          selCity:'选择市'
        })
      }
      if(index == 2){
        that.setData({
          districts: data,
          selCity: name,
          selDistrict:'选择区'
        })
      }
    }
  })
},

//省选择
bindProvince: function (e) {
  var item = this.data.provinces[e.detail.value]
  this.getRegion(1,item.id,item.name);
},
//市值选择
bindCity: function (e) {
  var that = this;
  var item = that.data.citys[e.detail.value]
  that.getRegion(2,item.id,item.name);
},  
bindCounty: function (e) {
  var that = this;
  var item = that.data.districts[e.detail.value]
  that.data.selDistrict = item.name;
},
showToast: function(title){
  wx.showToast({title: title, icon:'none'})
},
})